<?php

/**
 * ProductPricingApi
 * PHP version 8.3.
 *
 * @category Class
 *
 * @author   OpenAPI Generator team
 *
 * @see     https://openapi-generator.tech
 */

/**
 * Selling Partner API for Pricing.
 *
 * The Selling Partner API for Pricing helps you programmatically retrieve product pricing and offer pricing information for Amazon Marketplace products.  For more information, refer to the [Product Pricing v2022-05-01 Use Case Guide](https://developer-docs.amazon.com/sp-api/docs/product-pricing-api-v2022-05-01-use-case-guide).
 *
 * The version of the OpenAPI document: 2022-05-01
 * Generated by: https://openapi-generator.tech
 * Generator version: 7.9.0
 */

/**
 * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
 * https://openapi-generator.tech
 * Do not edit the class manually.
 */

namespace SpApi\Api\pricing\v2022_05_01;

use GuzzleHttp\Client;
use GuzzleHttp\ClientInterface;
use GuzzleHttp\Exception\ConnectException;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Promise\PromiseInterface;
use GuzzleHttp\Psr7\MultipartStream;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\RequestOptions;
use SpApi\ApiException;
use SpApi\AuthAndAuth\RestrictedDataTokenSigner;
use SpApi\Configuration;
use SpApi\HeaderSelector;
use SpApi\Model\pricing\v2022_05_01\CompetitiveSummaryBatchRequest;
use SpApi\Model\pricing\v2022_05_01\CompetitiveSummaryBatchResponse;
use SpApi\Model\pricing\v2022_05_01\GetFeaturedOfferExpectedPriceBatchRequest;
use SpApi\Model\pricing\v2022_05_01\GetFeaturedOfferExpectedPriceBatchResponse;
use SpApi\ObjectSerializer;
use Symfony\Component\RateLimiter\LimiterInterface;
use Symfony\Component\RateLimiter\RateLimiterFactory;
use Symfony\Component\RateLimiter\Storage\InMemoryStorage;

/**
 * ProductPricingApi Class Doc Comment.
 *
 * @category Class
 *
 * @author   OpenAPI Generator team
 *
 * @see     https://openapi-generator.tech
 */
class ProductPricingApi
{
    public ?LimiterInterface $getCompetitiveSummaryRateLimiter;
    public ?LimiterInterface $getFeaturedOfferExpectedPriceBatchRateLimiter;
    protected ClientInterface $client;

    protected Configuration $config;

    protected HeaderSelector $headerSelector;

    /**
     * @var int Host index
     */
    protected int $hostIndex;

    private bool $rateLimiterEnabled;
    private InMemoryStorage $rateLimitStorage;

    /**
     * @param int $hostIndex (Optional) host index to select the list of hosts if defined in the OpenAPI spec
     */
    public function __construct(
        Configuration $config,
        ?ClientInterface $client = null,
        ?bool $rateLimiterEnabled = true,
        ?HeaderSelector $selector = null,
        int $hostIndex = 0
    ) {
        $this->config = $config;
        $this->rateLimiterEnabled = $rateLimiterEnabled;

        if ($rateLimiterEnabled) {
            $this->rateLimitStorage = new InMemoryStorage();

            $factory = new RateLimiterFactory(Configuration::getRateLimitOptions('ProductPricingApi-getCompetitiveSummary'), $this->rateLimitStorage);
            $this->getCompetitiveSummaryRateLimiter = $factory->create('ProductPricingApi-getCompetitiveSummary');
            $factory = new RateLimiterFactory(Configuration::getRateLimitOptions('ProductPricingApi-getFeaturedOfferExpectedPriceBatch'), $this->rateLimitStorage);
            $this->getFeaturedOfferExpectedPriceBatchRateLimiter = $factory->create('ProductPricingApi-getFeaturedOfferExpectedPriceBatch');
        }

        $this->client = $client ?: new Client();
        $this->headerSelector = $selector ?: new HeaderSelector();
        $this->hostIndex = $hostIndex;
    }

    /**
     * Set the host index.
     *
     * @param int $hostIndex Host index (required)
     */
    public function setHostIndex(int $hostIndex): void
    {
        $this->hostIndex = $hostIndex;
    }

    /**
     * Get the host index.
     *
     * @return int Host index
     */
    public function getHostIndex(): int
    {
        return $this->hostIndex;
    }

    public function getConfig(): Configuration
    {
        return $this->config;
    }

    /**
     * Operation getCompetitiveSummary.
     *
     * @param CompetitiveSummaryBatchRequest $requests
     *                                                            The batch of &#x60;getCompetitiveSummary&#x60; requests. (required)
     * @param null|string                    $restrictedDataToken Restricted Data Token (RDT) for accessing restricted resources (optional, required for operations that return PII)
     *
     * @throws ApiException              on non-2xx response
     * @throws \InvalidArgumentException
     */
    public function getCompetitiveSummary(
        CompetitiveSummaryBatchRequest $requests,
        ?string $restrictedDataToken = null
    ): CompetitiveSummaryBatchResponse {
        list($response) = $this->getCompetitiveSummaryWithHttpInfo($requests, $restrictedDataToken);

        return $response;
    }

    /**
     * Operation getCompetitiveSummaryWithHttpInfo.
     *
     * @param CompetitiveSummaryBatchRequest $requests
     *                                                            The batch of &#x60;getCompetitiveSummary&#x60; requests. (required)
     * @param null|string                    $restrictedDataToken Restricted Data Token (RDT) for accessing restricted resources (optional, required for operations that return PII)
     *
     * @return array of \SpApi\Model\pricing\v2022_05_01\CompetitiveSummaryBatchResponse, HTTP status code, HTTP response headers (array of strings)
     *
     * @throws ApiException              on non-2xx response
     * @throws \InvalidArgumentException
     */
    public function getCompetitiveSummaryWithHttpInfo(
        CompetitiveSummaryBatchRequest $requests,
        ?string $restrictedDataToken = null
    ): array {
        $request = $this->getCompetitiveSummaryRequest($requests);
        if (null !== $restrictedDataToken) {
            $request = RestrictedDataTokenSigner::sign($request, $restrictedDataToken, 'ProductPricingApi-getCompetitiveSummary');
        } else {
            $request = $this->config->sign($request);
        }

        try {
            $options = $this->createHttpClientOption();

            try {
                if ($this->rateLimiterEnabled) {
                    $this->getCompetitiveSummaryRateLimiter->consume()->ensureAccepted();
                }
                $response = $this->client->send($request, $options);
            } catch (RequestException $e) {
                throw new ApiException(
                    "[{$e->getCode()}] {$e->getResponse()->getBody()}",
                    (int) $e->getCode(),
                    $e->getResponse() ? $e->getResponse()->getHeaders() : null,
                    $e->getResponse() ? (string) $e->getResponse()->getBody() : null
                );
            } catch (ConnectException $e) {
                throw new ApiException(
                    "[{$e->getCode()}] {$e->getMessage()}",
                    (int) $e->getCode(),
                    null,
                    null
                );
            }

            $statusCode = $response->getStatusCode();

            if ($statusCode < 200 || $statusCode > 299) {
                throw new ApiException(
                    sprintf(
                        '[%d] Error connecting to the API (%s)',
                        $statusCode,
                        (string) $request->getUri()
                    ),
                    $statusCode,
                    $response->getHeaders(),
                    (string) $response->getBody()
                );
            }
            if ('\SpApi\Model\pricing\v2022_05_01\CompetitiveSummaryBatchResponse' === '\SplFileObject') {
                $content = $response->getBody(); // stream goes to serializer
            } else {
                $content = (string) $response->getBody();
                if ('\SpApi\Model\pricing\v2022_05_01\CompetitiveSummaryBatchResponse' !== 'string') {
                    $content = json_decode($content);
                }
            }

            return [
                ObjectSerializer::deserialize($content, '\SpApi\Model\pricing\v2022_05_01\CompetitiveSummaryBatchResponse', []),
                $response->getStatusCode(),
                $response->getHeaders(),
            ];
        } catch (ApiException $e) {
            $data = ObjectSerializer::deserialize(
                $e->getResponseBody(),
                '\SpApi\Model\pricing\v2022_05_01\Errors',
                $e->getResponseHeaders()
            );
            $e->setResponseObject($data);

            throw $e;
        }
    }

    /**
     * Operation getCompetitiveSummaryAsync.
     *
     * @param CompetitiveSummaryBatchRequest $requests
     *                                                 The batch of &#x60;getCompetitiveSummary&#x60; requests. (required)
     *
     * @throws \InvalidArgumentException
     */
    public function getCompetitiveSummaryAsync(
        CompetitiveSummaryBatchRequest $requests
    ): PromiseInterface {
        return $this->getCompetitiveSummaryAsyncWithHttpInfo($requests)
            ->then(
                function ($response) {
                    return $response[0];
                }
            )
        ;
    }

    /**
     * Operation getCompetitiveSummaryAsyncWithHttpInfo.
     *
     * @param CompetitiveSummaryBatchRequest $requests
     *                                                 The batch of &#x60;getCompetitiveSummary&#x60; requests. (required)
     *
     * @throws \InvalidArgumentException
     */
    public function getCompetitiveSummaryAsyncWithHttpInfo(
        CompetitiveSummaryBatchRequest $requests,
        ?string $restrictedDataToken = null
    ): PromiseInterface {
        $returnType = '\SpApi\Model\pricing\v2022_05_01\CompetitiveSummaryBatchResponse';
        $request = $this->getCompetitiveSummaryRequest($requests);
        if (null !== $restrictedDataToken) {
            $request = RestrictedDataTokenSigner::sign($request, $restrictedDataToken, 'ProductPricingApi-getCompetitiveSummary');
        } else {
            $request = $this->config->sign($request);
        }
        if ($this->rateLimiterEnabled) {
            $this->getCompetitiveSummaryRateLimiter->consume()->ensureAccepted();
        }

        return $this->client
            ->sendAsync($request, $this->createHttpClientOption())
            ->then(
                function ($response) use ($returnType) {
                    if ('\SplFileObject' === $returnType) {
                        $content = $response->getBody(); // stream goes to serializer
                    } else {
                        $content = (string) $response->getBody();
                        if ('string' !== $returnType) {
                            $content = json_decode($content);
                        }
                    }

                    return [
                        ObjectSerializer::deserialize($content, $returnType, []),
                        $response->getStatusCode(),
                        $response->getHeaders(),
                    ];
                },
                function ($exception) {
                    $response = $exception->getResponse();
                    $statusCode = $response->getStatusCode();

                    throw new ApiException(
                        sprintf(
                            '[%d] Error connecting to the API (%s)',
                            $statusCode,
                            $exception->getRequest()->getUri()
                        ),
                        $statusCode,
                        $response->getHeaders(),
                        (string) $response->getBody()
                    );
                }
            )
        ;
    }

    /**
     * Create request for operation 'getCompetitiveSummary'.
     *
     * @param CompetitiveSummaryBatchRequest $requests
     *                                                 The batch of &#x60;getCompetitiveSummary&#x60; requests. (required)
     *
     * @throws \InvalidArgumentException
     */
    public function getCompetitiveSummaryRequest(
        CompetitiveSummaryBatchRequest $requests
    ): Request {
        // verify the required parameter 'requests' is set
        if (null === $requests || (is_array($requests) && 0 === count($requests))) {
            throw new \InvalidArgumentException(
                'Missing the required parameter $requests when calling getCompetitiveSummary'
            );
        }

        $resourcePath = '/batches/products/pricing/2022-05-01/items/competitiveSummary';
        $formParams = [];
        $queryParams = [];
        $headerParams = [];
        $httpBody = '';
        $multipart = false;

        $headers = $this->headerSelector->selectHeaders(
            ['application/json'],
            'application/json',
            $multipart
        );

        // for model (json/xml)
        if (isset($requests)) {
            if ('application/json' === $headers['Content-Type']) {
                $httpBody = \GuzzleHttp\json_encode(ObjectSerializer::sanitizeForSerialization($requests));
            } else {
                $httpBody = $requests;
            }
        } elseif (count($formParams) > 0) {
            if ($multipart) {
                $multipartContents = [];
                foreach ($formParams as $formParamName => $formParamValue) {
                    $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue];
                    foreach ($formParamValueItems as $formParamValueItem) {
                        $multipartContents[] = [
                            'name' => $formParamName,
                            'contents' => $formParamValueItem,
                        ];
                    }
                }
                // for HTTP post (form)
                $httpBody = new MultipartStream($multipartContents);
            } elseif ('application/json' === $headers['Content-Type']) {
                $httpBody = \GuzzleHttp\json_encode($formParams);
            } else {
                // for HTTP post (form)
                $httpBody = ObjectSerializer::buildQuery($formParams, $this->config);
            }
        }

        $defaultHeaders = [];
        if ($this->config->getUserAgent()) {
            $defaultHeaders['User-Agent'] = $this->config->getUserAgent();
        }

        $headers = array_merge(
            $defaultHeaders,
            $headerParams,
            $headers
        );

        $query = ObjectSerializer::buildQuery($queryParams, $this->config);

        return new Request(
            'POST',
            $this->config->getHost().$resourcePath.($query ? "?{$query}" : ''),
            $headers,
            $httpBody
        );
    }

    /**
     * Operation getFeaturedOfferExpectedPriceBatch.
     *
     * @param GetFeaturedOfferExpectedPriceBatchRequest $get_featured_offer_expected_price_batch_request_body
     *                                                                                                        The batch of &#x60;getFeaturedOfferExpectedPrice&#x60; requests. (required)
     * @param null|string                               $restrictedDataToken                                  Restricted Data Token (RDT) for accessing restricted resources (optional, required for operations that return PII)
     *
     * @throws ApiException              on non-2xx response
     * @throws \InvalidArgumentException
     */
    public function getFeaturedOfferExpectedPriceBatch(
        GetFeaturedOfferExpectedPriceBatchRequest $get_featured_offer_expected_price_batch_request_body,
        ?string $restrictedDataToken = null
    ): GetFeaturedOfferExpectedPriceBatchResponse {
        list($response) = $this->getFeaturedOfferExpectedPriceBatchWithHttpInfo($get_featured_offer_expected_price_batch_request_body, $restrictedDataToken);

        return $response;
    }

    /**
     * Operation getFeaturedOfferExpectedPriceBatchWithHttpInfo.
     *
     * @param GetFeaturedOfferExpectedPriceBatchRequest $get_featured_offer_expected_price_batch_request_body
     *                                                                                                        The batch of &#x60;getFeaturedOfferExpectedPrice&#x60; requests. (required)
     * @param null|string                               $restrictedDataToken                                  Restricted Data Token (RDT) for accessing restricted resources (optional, required for operations that return PII)
     *
     * @return array of \SpApi\Model\pricing\v2022_05_01\GetFeaturedOfferExpectedPriceBatchResponse, HTTP status code, HTTP response headers (array of strings)
     *
     * @throws ApiException              on non-2xx response
     * @throws \InvalidArgumentException
     */
    public function getFeaturedOfferExpectedPriceBatchWithHttpInfo(
        GetFeaturedOfferExpectedPriceBatchRequest $get_featured_offer_expected_price_batch_request_body,
        ?string $restrictedDataToken = null
    ): array {
        $request = $this->getFeaturedOfferExpectedPriceBatchRequest($get_featured_offer_expected_price_batch_request_body);
        if (null !== $restrictedDataToken) {
            $request = RestrictedDataTokenSigner::sign($request, $restrictedDataToken, 'ProductPricingApi-getFeaturedOfferExpectedPriceBatch');
        } else {
            $request = $this->config->sign($request);
        }

        try {
            $options = $this->createHttpClientOption();

            try {
                if ($this->rateLimiterEnabled) {
                    $this->getFeaturedOfferExpectedPriceBatchRateLimiter->consume()->ensureAccepted();
                }
                $response = $this->client->send($request, $options);
            } catch (RequestException $e) {
                throw new ApiException(
                    "[{$e->getCode()}] {$e->getResponse()->getBody()}",
                    (int) $e->getCode(),
                    $e->getResponse() ? $e->getResponse()->getHeaders() : null,
                    $e->getResponse() ? (string) $e->getResponse()->getBody() : null
                );
            } catch (ConnectException $e) {
                throw new ApiException(
                    "[{$e->getCode()}] {$e->getMessage()}",
                    (int) $e->getCode(),
                    null,
                    null
                );
            }

            $statusCode = $response->getStatusCode();

            if ($statusCode < 200 || $statusCode > 299) {
                throw new ApiException(
                    sprintf(
                        '[%d] Error connecting to the API (%s)',
                        $statusCode,
                        (string) $request->getUri()
                    ),
                    $statusCode,
                    $response->getHeaders(),
                    (string) $response->getBody()
                );
            }
            if ('\SpApi\Model\pricing\v2022_05_01\GetFeaturedOfferExpectedPriceBatchResponse' === '\SplFileObject') {
                $content = $response->getBody(); // stream goes to serializer
            } else {
                $content = (string) $response->getBody();
                if ('\SpApi\Model\pricing\v2022_05_01\GetFeaturedOfferExpectedPriceBatchResponse' !== 'string') {
                    $content = json_decode($content);
                }
            }

            return [
                ObjectSerializer::deserialize($content, '\SpApi\Model\pricing\v2022_05_01\GetFeaturedOfferExpectedPriceBatchResponse', []),
                $response->getStatusCode(),
                $response->getHeaders(),
            ];
        } catch (ApiException $e) {
            $data = ObjectSerializer::deserialize(
                $e->getResponseBody(),
                '\SpApi\Model\pricing\v2022_05_01\Errors',
                $e->getResponseHeaders()
            );
            $e->setResponseObject($data);

            throw $e;
        }
    }

    /**
     * Operation getFeaturedOfferExpectedPriceBatchAsync.
     *
     * @param GetFeaturedOfferExpectedPriceBatchRequest $get_featured_offer_expected_price_batch_request_body
     *                                                                                                        The batch of &#x60;getFeaturedOfferExpectedPrice&#x60; requests. (required)
     *
     * @throws \InvalidArgumentException
     */
    public function getFeaturedOfferExpectedPriceBatchAsync(
        GetFeaturedOfferExpectedPriceBatchRequest $get_featured_offer_expected_price_batch_request_body
    ): PromiseInterface {
        return $this->getFeaturedOfferExpectedPriceBatchAsyncWithHttpInfo($get_featured_offer_expected_price_batch_request_body)
            ->then(
                function ($response) {
                    return $response[0];
                }
            )
        ;
    }

    /**
     * Operation getFeaturedOfferExpectedPriceBatchAsyncWithHttpInfo.
     *
     * @param GetFeaturedOfferExpectedPriceBatchRequest $get_featured_offer_expected_price_batch_request_body
     *                                                                                                        The batch of &#x60;getFeaturedOfferExpectedPrice&#x60; requests. (required)
     *
     * @throws \InvalidArgumentException
     */
    public function getFeaturedOfferExpectedPriceBatchAsyncWithHttpInfo(
        GetFeaturedOfferExpectedPriceBatchRequest $get_featured_offer_expected_price_batch_request_body,
        ?string $restrictedDataToken = null
    ): PromiseInterface {
        $returnType = '\SpApi\Model\pricing\v2022_05_01\GetFeaturedOfferExpectedPriceBatchResponse';
        $request = $this->getFeaturedOfferExpectedPriceBatchRequest($get_featured_offer_expected_price_batch_request_body);
        if (null !== $restrictedDataToken) {
            $request = RestrictedDataTokenSigner::sign($request, $restrictedDataToken, 'ProductPricingApi-getFeaturedOfferExpectedPriceBatch');
        } else {
            $request = $this->config->sign($request);
        }
        if ($this->rateLimiterEnabled) {
            $this->getFeaturedOfferExpectedPriceBatchRateLimiter->consume()->ensureAccepted();
        }

        return $this->client
            ->sendAsync($request, $this->createHttpClientOption())
            ->then(
                function ($response) use ($returnType) {
                    if ('\SplFileObject' === $returnType) {
                        $content = $response->getBody(); // stream goes to serializer
                    } else {
                        $content = (string) $response->getBody();
                        if ('string' !== $returnType) {
                            $content = json_decode($content);
                        }
                    }

                    return [
                        ObjectSerializer::deserialize($content, $returnType, []),
                        $response->getStatusCode(),
                        $response->getHeaders(),
                    ];
                },
                function ($exception) {
                    $response = $exception->getResponse();
                    $statusCode = $response->getStatusCode();

                    throw new ApiException(
                        sprintf(
                            '[%d] Error connecting to the API (%s)',
                            $statusCode,
                            $exception->getRequest()->getUri()
                        ),
                        $statusCode,
                        $response->getHeaders(),
                        (string) $response->getBody()
                    );
                }
            )
        ;
    }

    /**
     * Create request for operation 'getFeaturedOfferExpectedPriceBatch'.
     *
     * @param GetFeaturedOfferExpectedPriceBatchRequest $get_featured_offer_expected_price_batch_request_body
     *                                                                                                        The batch of &#x60;getFeaturedOfferExpectedPrice&#x60; requests. (required)
     *
     * @throws \InvalidArgumentException
     */
    public function getFeaturedOfferExpectedPriceBatchRequest(
        GetFeaturedOfferExpectedPriceBatchRequest $get_featured_offer_expected_price_batch_request_body
    ): Request {
        // verify the required parameter 'get_featured_offer_expected_price_batch_request_body' is set
        if (null === $get_featured_offer_expected_price_batch_request_body || (is_array($get_featured_offer_expected_price_batch_request_body) && 0 === count($get_featured_offer_expected_price_batch_request_body))) {
            throw new \InvalidArgumentException(
                'Missing the required parameter $get_featured_offer_expected_price_batch_request_body when calling getFeaturedOfferExpectedPriceBatch'
            );
        }

        $resourcePath = '/batches/products/pricing/2022-05-01/offer/featuredOfferExpectedPrice';
        $formParams = [];
        $queryParams = [];
        $headerParams = [];
        $httpBody = '';
        $multipart = false;

        $headers = $this->headerSelector->selectHeaders(
            ['application/json'],
            'application/json',
            $multipart
        );

        // for model (json/xml)
        if (isset($get_featured_offer_expected_price_batch_request_body)) {
            if ('application/json' === $headers['Content-Type']) {
                $httpBody = \GuzzleHttp\json_encode(ObjectSerializer::sanitizeForSerialization($get_featured_offer_expected_price_batch_request_body));
            } else {
                $httpBody = $get_featured_offer_expected_price_batch_request_body;
            }
        } elseif (count($formParams) > 0) {
            if ($multipart) {
                $multipartContents = [];
                foreach ($formParams as $formParamName => $formParamValue) {
                    $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue];
                    foreach ($formParamValueItems as $formParamValueItem) {
                        $multipartContents[] = [
                            'name' => $formParamName,
                            'contents' => $formParamValueItem,
                        ];
                    }
                }
                // for HTTP post (form)
                $httpBody = new MultipartStream($multipartContents);
            } elseif ('application/json' === $headers['Content-Type']) {
                $httpBody = \GuzzleHttp\json_encode($formParams);
            } else {
                // for HTTP post (form)
                $httpBody = ObjectSerializer::buildQuery($formParams, $this->config);
            }
        }

        $defaultHeaders = [];
        if ($this->config->getUserAgent()) {
            $defaultHeaders['User-Agent'] = $this->config->getUserAgent();
        }

        $headers = array_merge(
            $defaultHeaders,
            $headerParams,
            $headers
        );

        $query = ObjectSerializer::buildQuery($queryParams, $this->config);

        return new Request(
            'POST',
            $this->config->getHost().$resourcePath.($query ? "?{$query}" : ''),
            $headers,
            $httpBody
        );
    }

    /**
     * Create http client option.
     *
     * @return array of http client options
     *
     * @throws \RuntimeException on file opening failure
     */
    protected function createHttpClientOption(): array
    {
        $options = [];
        if ($this->config->getDebug()) {
            $options[RequestOptions::DEBUG] = fopen($this->config->getDebugFile(), 'a');
            if (!$options[RequestOptions::DEBUG]) {
                throw new \RuntimeException('Failed to open the debug file: '.$this->config->getDebugFile());
            }
        }

        return $options;
    }
}
